package com.oauth2.demo2.oauth2;

import com.oauth2.demo2.authentication.AuthLimitHandler;
import com.oauth2.demo2.authentication.AuthenticationFailureHandler;
import com.oauth2.demo2.authentication.AuthenticationSuccessHandler;
import com.oauth2.demo2.utils.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

/**
 * @ClassName MyResourceConfig
 * @Description 资源服务器配置
 * @Author Liujt
 * @Date 2020/1/16 11:34
 **/
@Configuration
@EnableResourceServer
public class MyResourceConfig extends ResourceServerConfigurerAdapter {
    //登录成功处理
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    //登录失败处理
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    //权限不足处理器
    @Autowired
    private AuthLimitHandler authLimitHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //安全配置
        http.formLogin()
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)//访问的资源需要认证处理逻辑
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)//登录地址
                .successHandler(authenticationSuccessHandler)//登录成功处理
                .failureHandler(authenticationFailureHandler)

                //权限控制
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/user/*")
                .access("hasRole('ADMIN')")//此请求需要ADMIN权限访问
                //不需要拦截
                .antMatchers(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                        SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/*",
                        SecurityConstants.DEFAULT_SESSION_INVALID_URL/*,
                        "/oauth/*"*/)
                .permitAll()
                .anyRequest()
                .authenticated();

        // 用户权限不足处理器
        http.exceptionHandling().accessDeniedHandler(authLimitHandler);


        //攻击防护: 关闭
        http.csrf().disable();
    }

}